import logging

import pytest

from resource.pom.settings import Settings
from utils.manager import Images


class Test:
    app = Settings

    @pytest.mark.parametrize('setup_teardown', [app.bundle_name], indirect=True)
    def test(self, setup_teardown, device):
        logging.info('步骤1.点击设置应用')
        device.start_ability(self.app.bundle_name, self.app.ability_name)
        logging.info('预期结果1.进入设置界面')
        device.assert_current_window(self.app.window_name)

        logging.info('步骤2.点击隐私')
        device.click(*self.app.privacy_item)
        logging.info('预期结果2.进入隐私')
        device.refresh_layout()
        device.assert_text_exist('权限管理')

        logging.info('步骤3.点击权限管理，点击权限')
        device.click_element(device.get_element_by_text('权限管理'))
        device.refresh_layout()
        device.click_element(device.get_element_by_text('权限'))
        logging.info('预期结果3.进入权限管理-权限')
        device.refresh_layout()
        device.assert_text_exist('位置信息')
        device.assert_text_exist('相机')
        device.assert_text_exist('麦克风')

        logging.info('步骤4.反复上下滑动权限列表，左右滑动或点击应用、权限切换')
        device.swipe(360, 640, 360, 300)
        device.swipe(500, 640, 100, 640)
        logging.info('预期结果4.可以上下左右滑动或点击权限/应用，无卡死、黑屏、白屏现象')
        device.refresh_layout()
        device.assert_type_exist('TextInput')

        logging.info('步骤5.点击进入权限列表中某一内容列，应用权限搜索、按钮开启关闭')
        device.swipe(100, 640, 500, 640)
        device.swipe(360, 600, 360, 900)
        device.refresh_layout()
        device.click_element(device.get_element_by_text('读取已安装应用列表'))
        logging.info('预期结果5.应用权限搜索、按钮开启关闭生效无异常')
        device.refresh_layout()
        device.click_element(device.get_element_by_type('TextInput'))
        device.wait(1)
        device.assert_soft_keyboard_on()
        device.go_back()
        toggle = device.get_element_by_type('Toggle')
        element_area = device.get_element_area(toggle)
        # 截图
        before_click = device.save_snapshot_to_local('before_click.jpeg')
        before_click = Images.crop_picture(before_click, *element_area)
        switch_status0 = toggle.get('checked')
        device.click_element(toggle)
        device.refresh_layout()
        toggle = device.get_element_by_type('Toggle')
        switch_status1 = toggle.get('checked')
        # 截图
        after_click = device.save_snapshot_to_local('after_click.jpeg')
        after_click = Images.crop_picture(after_click, *element_area)
        logging.info('开关状态变化: {}->{}'.format(switch_status0, switch_status1))
        device.click_element(toggle)
        assert switch_status0 != switch_status1, '按钮开启或关闭无效'
        similarity = Images.compare_image_similarity(before_click, after_click)
        assert similarity < 0.8, '点击前后界面显示的开关状态未变'
